package org.eclipse.swt.widgets;

import com.mephi.oshs.model.entry.IEntry;
import com.mephi.oshs.model.style.IStyle;
import com.mephi.oshs.model.style.StyleFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Image;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Observable;
import java.util.Observer;

public class EntryTreeItem<T extends IEntry> extends TreeItem implements Observer {

    private static final Logger logger = LoggerFactory.getLogger(EntryTreeItem.class);

    private T entry;

    public EntryTreeItem(Tree parent, T entry) {
        super(parent, SWT.NONE);
        this.setEntry(entry);
    }

    public EntryTreeItem(TreeItem parentItem, T entry) {
        super(parentItem, SWT.NONE);
        this.setEntry(entry);
    }

    public T getEntry() {
        return this.entry;
    }

    public void setEntry(final T entry) {

        // Сначала отписываемся от прошлой entry.
        if (this.entry != null) {
            this.entry.deleteObserver(this);
        }

        // Подписываемся на новую entry.
        this.entry = entry;
        entry.addObserver(this);
        this.update();
    }

    /*default*/ void update() {
        this.updateText(entry.getShortName());
        this.updateStyle(entry.getStyle());
    }

    private void updateText(final String text) {
        if (text != null) {
            super.setText(text);
        }
    }

    private void updateStyle(final IStyle style) {
        if (style != null && !style.useDefaults()) {
            Color color;
            Image image;
            Font font;
            if ((color = style.getBackgroundColor()) != null) {
                super.setBackground(color);
            }
            if ((color = style.getForegroundColor()) != null) {
                super.setForeground(color);
            }
            if ((image = style.getImage()) != null) {
                super.setImage(image);
            }
            if ((font = style.getFont()) != null) {
                super.setFont(font);
            }
        } else {
            super.setImage(StyleFactory.getBlankImage());
            logger.debug("updateStyle(): No style for entry: " + entry);
        }
    }

    @Override
    public void update(Observable o, Object arg) {
        if (o instanceof IEntry) {
            this.update();
        } else {
            throw new IllegalArgumentException("setTree(): Observer doesn't support observable class: "
                    + o.getClass().getCanonicalName());
        }
    }
}
